// 引入action
import { incrementAction, incrementAsync, decrementAction } from "../redux/count_actions"
// 从react-redux中引入connect方法
import { connect } from "react-redux"

import React, { Component } from 'react'
class Count extends Component {

  changeCount = (type) => {
    const { increment, decrement, incrementAsync } = this.props
    return () => {
      if (type === 'incrementIfOdd') {
        if (this.props.count % 2 !== 0) {
          increment(this.select.value * 1)
        }
      } else if (type === 'incrementAsync') {
        incrementAsync(this.select.value * 1)
      } else if (type === 'increment') {
        increment(this.select.value * 1)

      } else if (type === 'decrement') {
        decrement(this.select.value * 1)
      }
    }
  }
  render() {
    console.log(this.props)
    return (
      <div>
        <h2>当前计数:{this.props.count}, 总共有{this.props.personNumber}人</h2>
        <select ref={c => this.select = c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        <button onClick={this.changeCount('increment')}>+</button>&nbsp;
        <button onClick={this.changeCount('decrement')}>-</button>&nbsp;
        <button onClick={this.changeCount('incrementIfOdd')}>计数再加</button>&nbsp;
        <button onClick={this.changeCount('incrementAsync')}>异步相加</button>&nbsp;
      </div>
    )
  }
}



// 将action通过props传递到ui组件
function mapActionToProps(state) {
  return { count: state.count, personNumber: state.person.length }
}

// 将dispatch通过props传递到ui组件
function mapDispatchToProps(dispatch) {
  return {
    increment: (data) => dispatch(incrementAction(data)),
    decrement: (data) => dispatch(decrementAction(data)),
    incrementAsync: (data) => dispatch(incrementAsync(data))
  }
}


export default connect(mapActionToProps, mapDispatchToProps)(Count)